<?php
namespace Crm\Domain;

use Crm\Common\MetaData as MetaData;
use Crm\Common\Util as Util;
use Crm\Common\Pager as Pager;

class SysUser
{
    /**
     * ado连接。
     *
     * @var object
     * @access pdo
     */
    public $pdo;

    public $metaData;
    public $baseCode;

    public $key='fc114';          //key值 数据库保存md5值格式为:md5(密码+key) 防止破译md5

    public function __construct()
    {
        $this->pdo = \PhalApi\DI()->pdo;

        $this->baseCode = (object)\PhalApi\DI()->config->get('basecode');
        $this->province_code = \PhalApi\DI()->config->get('app.provinceCode');//省
        $this->city_code = \PhalApi\DI()->config->get('app.cityCode');//城市

        $this->metaData = new MetaData();
    }

    /* 获取搜索用户列表 */
    public function getUserList($param,$pageSize=10){
        $page_info = "";
        $orderField = isset($param['sort']) ? $param['sort'] : 'id';
        $orderValue = isset($param['sort_value']) ? $param['sort_value'] : 'desc';

        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($param['page']) ? (int)$param['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = ' where is_admin!=1 and flag=1 ';

        $filter = array();//筛选条件
        $filter['sort'] = $orderField;
        $filter['sort_value'] = $orderValue;
        $filter['parent_id'] = $param['parent_id'];
        $page_info .="sort=".$orderField."&sort_value=".$orderValue."&";

        $filter['keyword'] = isset($param['keyword']) ? $param['keyword'] : '';
        if($filter['keyword'] != ''){
            $where .=" and (user_name like '%{$filter['keyword']}%' or true_name like '%{$filter['keyword']}%')";
            $page_info.="keyword={$filter['keyword']}&";

        }

        $filter['active'] = isset($param['active']) ? $param['active'] : 1;
        if($filter['active']>=0){
            $where .=" and active=".$filter['active'];
            $page_info.="active={$filter['active']}&";
        }

        $this->loadModel('cyzt_companylist');
        //处理搜索条件
        $filter['parent_id'] = $param['parent_id'];
        if(isset($param['parent_id']) && $param['parent_id']>0){
            //判断传入的parent_id是部门,还是岗位
            $orgStrInfo = $this->cyzt_companylist->getOrgStructInfoById($param['parent_id']);
            //根据orgstruct_id从sys_orgstruct表中获取对应的孩子orgstruct_id;
            $orgstruct_id = $param['parent_id'];
            $orgList = $this->cyzt_companylist->getSubOrgList($orgstruct_id);
            if(count($orgList)>0){
                $orgRoles = '';
                foreach ($orgList as $item){
                    $orgRoles .= $item['id'].',';
                }
                $orgRoles=substr($orgRoles,0,-1);
                if($orgStrInfo['type']=='job') {
                    $where .= " and orgstruct_id in($orgstruct_id," . $orgRoles . ")";
                }else{
                    $where .= " and department_id in($orgstruct_id," . $orgRoles . ")";
                }
            }else{
                if($orgStrInfo['type']=='job') {
                    $where .= " and orgstruct_id=" . $orgstruct_id;
                }else{
                    $where .= " and department_id=" . $orgstruct_id;
                }
            }
            $page_info.="parent_id={$param['parent_id']}&";
        }

        $select_columns = "select %s from sys_user as u %s %s";
        $order = "order by $orderField $orderValue";
        $sql = sprintf($select_columns,'u.id,u.orgstruct_id,u.department_id,u.user_name,u.true_name,u.user_type,u.active,u.is_admin,u.ratio',$where,$order);
        $rs['data'] = $this->pdo->selectLimit($sql,$pageSize,$offset);
        $recordCount = $this->pdo->getCount();
        $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,3);
        $rs['pageStr']=$page->get_page_html();
        foreach($rs['data'] as $key=>$item){
            if($item['orgstruct_id']>0){
                $orgStr= $this->cyzt_companylist->getOrgStruct($item['orgstruct_id']);
                $rs['data'][$key]['org_pos'] = $orgStr;
                foreach ($orgStr as $item2) {
                    if (!isset($rs['data'][$key]['poststaion']) && $item2['org_type'] == 'job') $rs['data'][$key]['poststaion'] = $item2['org_name'];
                    if (!isset($rs['data'][$key]['department']) && $item2['org_type'] == 'department') $rs['data'][$key]['department'] = $item2['org_name'];
                    if (!isset($rs['data'][$key]['company']) && $item2['org_type'] == 'company') $rs['data'][$key]['company'] = $item2['org_name'];
                }
            }
        }

        $rs['filter'] = $filter;
        $rs['cnt'] = $recordCount;
        $rs['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        return $rs;
    }

    /* 保存用户 */
    public function savePerson($record,$act='add'){
        //判断用户名是否存在
        $sql="select count(id) as cnt from sys_user where user_name='".$record["user_name"]."'";
        $user_info=$this->pdo->getRow($sql);
        if($user_info['cnt']>0 and $act=='add'){
            $rlt["res"]=0;
            $rlt["msg"]="用户名已存在！";
        }else if($_SESSION["isadmin"]=="0" && $record["user_type"]=="1"){
            $rlt["res"]=0;
            $rlt["msg"]="您没有权限！";
        }else{
            $record["write_date"]=time();
            $record["write_uid"]=$this->session->user_id;
            $password = md5(trim($record["password"]).$this->key);
            //如果密码未更改则不需要更新
            isset($record['password'])?$record['password']=Util::encrypt($password):'';
            if($act=='add'){
                unset($record['id']);

                $record["create_uid"]=$this->session->user_id;
                $record["create_date"]=time();

                $record["status"]=1;
                $record["is_admin"]=0;
                $record["flag"]=1;

                $insert_Id = $this->pdo->add($record,'sys_user');
                $rlt["res"]=$insert_Id;
                $rlt["msg"]=$insert_Id?"":"新增用户失败！";
            }else{
                $Affected_Rows= $this->pdo->update($record,'sys_user','id='.$record['id']);
                $rlt["res"]=$Affected_Rows;
                $rlt["msg"]=$Affected_Rows?"":"更新用户失败！";
            }
        }
        return $rlt;
    }

    /* 根据名字查找用户列表 */
    public function getUserListByName($name='',$field="id,true_name"){
        $list = array();
        if(!empty($name)) {
            $sql = "select ".$field." from sys_user where true_name like '%{$name}%'";
            $list = $this->pdo->getAll($sql);
        }
        return $list;
    }

    /* 根据用户ID获取用户名 */
    public function getUserNameById($id,$field="id,true_name"){
        if(!empty($id)) {
            $ids = explode(",", $id);
            if (count($ids) > 1) {
                $_ids = '';
                foreach ($ids as $item) {
                    if ($item > 0) $_ids .= $item . ',';
                }
                $_ids = substr($_ids, 0, -1);
                if ($_ids != '') {
                    $sql = "select " . $field . " from sys_user where id in(" . $_ids . ")";
                    $rlt = $this->pdo->getAll($sql);
                }
            } else {
                $sql = "select " . $field . " from sys_user where id=" . $ids[0];
                $rlt = $this->pdo->getRow($sql);
            }
            return $rlt;
        }
        return false;
    }

    /* 获取用户信息 */
    public function getUserInfo($id,$field="*"){
        $sql = "select ".$field." from sys_user where flag=1 and id=".$id;
        $rs = $this->pdo->getRow($sql);
        if(isset($rs["password"]))$rs["password"]=Util::decrypt($rs["password"]);
        return $rs;
    }

    /* 获取用户信息*/
    public function getUserInfoByOpenId($openId,$filed = 'id'){
        $sql = "select ".$filed." from sys_user where openid='".$openId."'";
        $userInfo = $this->pdo->getRow($sql);
        return $userInfo;
    }

    /* 根据用户ID获取用户信息 */
    public function getUserInfoById($id){
        $sql = "select u.id,u.create_date,u.orgstruct_id,u.true_name,u.email,u.user_type,u.headimgurl,u.mobile,u.address,u.department_id,u.active,o.org_name,d.org_name as department_name
                from sys_user as u 
                LEFT JOIN sys_orgstruct as o on u.orgstruct_id=o.id 
                LEFT JOIN sys_orgstruct as d on u.department_id=d.id 
                where u.id=".$id;
        $rlt = $this->pdo->getRow($sql);
        //用户类型
        $user_type_class = Util::statusColor($rlt['user_type'],'badge');
        $rlt['user_type_val'] = '<span class="'.$user_type_class.'">'.$this->baseCode->user_type_option[$rlt['user_type']].'</span>';

        //用户状态
        $active_class = Util::statusColor($rlt['active']);
        $rlt['active_val'] = '<span class="'.$active_class.'">'.$this->baseCode->active_option[$rlt['active']].'</span>';

        $rlt['create_date_val'] = date('Y-m-d H:i:s',$rlt['create_date']);
        return $rlt;
    }

    /* 根据电话获取用户登录信息 */
    public function getUserInfoByMobile($mobile){
        $where = " a.mobile='".$mobile."'";
        $sql = "SELECT a.id,a.orgstruct_id,a.department_id,a.user_type,a.user_name,a.true_name,a.nickname,a.password,a.openid,a.headimgurl,a.mobile,a.is_admin,a.city_code,a.active,a.login_date,b.name as role_name,b.id as poststation_id FROM sys_user as a left join sys_poststation as b on a.orgstruct_id=b.orgstruct_id where ".$where;
        $rlt = $this->pdo->getRow($sql);
        return $rlt;
    }

    /* 根据用户ID获取该用户上级主管 */
    public function getSupUserInfoById($id){
        if(!empty($id) && $id>0) {
            //获取该用户的上级岗位
            $sql = "select u.orgstruct_id,u.true_name,o.parent_job_id from sys_user as u LEFT JOIN 
                sys_orgstruct as o on u.orgstruct_id=o.id where u.id=" . $id; //u.flag=1 and
            $user = $this->pdo->getRow($sql);
            //获取上级岗位下的人员
            $sql = "select id,true_name,orgstruct_id from sys_user where flag=1 and orgstruct_id=" . $user['parent_job_id'];
            $sup_user = $this->pdo->getRow($sql);
        }else{
            $sup_user = false;
        }
        return $sup_user;
    }

    /* 根据部门ID获取部门下的用户列表 */
    public function getUserListByDepartmentId($department_id,$type='list'){
        $sql = "select u.id,u.user_name,u.true_name,o.org_name from sys_user as u LEFT JOIN sys_orgstruct as o on u.orgstruct_id=o.id 
                where u.flag=1 and u.active=1 and u.department_id={$department_id}";
        $roleList = $this->pdo->getAll($sql);
        if($type=='list') {
            return $roleList;
        }else{
            foreach ($roleList as $key=>$value) {
                $role_ids[] = $value['id'];
            }
            return $role_ids;
        }
    }

    /* 根据名字查找下级用户列表 */
    public function getSubUserListByName($name='',$field="id,true_name"){
        $list = array();
        if(!empty($name)) {
            $sub_ids = $this->getSubUserIdByUserId($this->session->user_id,0);//下属员工
            $sub_ids_str = implode(',',$sub_ids);
            $sql = "select ".$field." from sys_user where true_name like '%{$name}%' and id in(".$sub_ids_str.")";
            $list = $this->pdo->getAll($sql);
        }
        return $list;
    }

    /* 根据用户类型获取用户列表 */
    public function getUserListByType($user_type){
        $owner_sql = "select id,true_name,user_name,user_type from sys_user where user_type=".$user_type;
        $ownerList = $this->pdo->getAll($owner_sql);
        foreach ($ownerList as $item){
            $rlt[$item['id']]=$item['true_name'];
        }
        return $rlt;
    }

    /* 获取用户下的所有用户
     * $self == 0 为获得当前用户下属所有人user_id
     * $self == 1 为获得当前用户下属所有人user_id,包括自己
     */
    public function getSubUserIdByUserId($user_id,$self=1){
        $sql = 'select id,user_name,orgstruct_id from sys_user where flag=1 and active=1 and id='.$user_id;
        $user = $this->pdo->getRow($sql);
        $commpany = new Company();
        $user_role = $commpany->getSubRoleList($user['orgstruct_id']);
        //下级用户
        $below_ids = array();
        if ($self) {
            $below_ids[] = $user_id;
        }
        if(count($user_role)>0) {
            $below_role = implode(',', $user_role);
            $sql = "select id,user_name,orgstruct_id from sys_user where flag=1 and active=1 and orgstruct_id in({$below_role})";
            $userlist = $this->pdo->getAll($sql);
            foreach ($userlist as $key=>$value) {
                $below_ids[] = $value['id'];
            }
        }
        return array_unique($below_ids);
    }

    /* 根据用户类型获取用户列表 */
    public function getUserListByUserType($user_type,$field="id,true_name"){
        $sql = "select ".$field." from sys_user where is_admin=0 and user_type in (".$user_type.")";
        $list = $this->pdo->getAll($sql);
        return $list;
    }

    /* 获取用户通讯录 */
    public function getUserBook($org_id=0){
        $sql = "select * from sys_orgstruct where (type='company' or type='department') and flag=1 and org_name<>'维护队'";
        $list = $this->pdo->getAll($sql);
        foreach ($list as $key=>$item){
            //获取部门下的员工
            $sql = "select id,true_name as name,mobile,headimgurl from sys_user where department_id=".$item['id']." and active=1 and flag=1";
            $userlist = $this->pdo->getAll($sql);
            $list[$key]['userlist'] = $userlist;
        }
        return $list;
    }

    /************* 统计相关 *******************/
    /* 根据用户ID获取用户的房源数、客源数、带看数 */
    public function getUserTotal($user_id){
       //房源数
       $sql = "select count(*) as cnt from fc_esf where owner_uid={$user_id} and flag=1";
       $esfNum = $this->pdo->getRow($sql);
       $sql = "select count(*) as cnt from crm_customer where owner_uid={$user_id} and flag=1";
       $customerNum = $this->pdo->getRow($sql);
       $sql = "select count(*) as cnt from crm_visit where owner_uid={$user_id} and flag=1";
       $visitNum = $this->pdo->getRow($sql);
       $rlt['esfNum'] = $esfNum['cnt'];
       $rlt['customerNum'] = $customerNum['cnt'];
       $rlt['visitNum'] = $visitNum['cnt'];
       return $rlt;
    }

    /************** 微信相关 ****************/
    /* 绑定微信 */
    public function bindOpenId($user_id,$openid){
        $data["openid"]=$openid;
        $affected_Rows= $this->pdo->update($data,'sys_user','id='.$user_id);
        $rlt["res"]=$affected_Rows;
        $rlt["msg"]=$affected_Rows?"绑定成功!":"绑定失败！";
        return $rlt;
    }

}
